//
//  QGUserCenter.m
//  qeegooChat
//
//  Created by heew on 16/1/7.
//  Copyright © 2016年 com.autozi. All rights reserved.
//

#import "QGUserCenter.h"
#import "QGUserModel.h"
#import "QGMessageExtendUserModel.h"


#define kZYUserCenterLoginUserDir     @"LoginUserDir"
#define kZYUserCenterLastLoginUserUDF @"kZYUserCenterLastLoginUserUDF"

@interface QGUserCenter ()

@property (nonatomic,strong)QGUserModel *innerLoginUser;

@property (nonatomic,strong)QGMessageExtendUserModel *innerExtendUserInfo;

@end

@implementation QGUserCenter
+ (QGUserCenter *)shareCenter
{
    static QGUserCenter *_instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        if (!_instance) {
            _instance = [[self alloc]init];
        }
    });
    
    return _instance;
}

- (instancetype)init
{
    if (self = [super init]) {
        
        [self readLastLoginUser];
    }
    return self;
}

- (void)LoginUserWithMobile:(NSString *)mobile withPassword:(NSString *)password withSuccess:(ZYUserCenterRequestSuccessBlock)success withFaild:(ZYUserCenterRequestFaildBlock)faild
{
    [self loginEaseMobWithMobile:mobile password:password];
}


- (QGUserModel *)currentLoginUser
{
    return self.innerLoginUser;
}

- (BOOL)isLogin
{
    return self.innerLoginUser? YES:NO;
}

- (NSString *)userSavePath:(NSString *)userId
{
    NSString *cacheDir = QGAppCachePath(kZYUserCenterLoginUserDir);
    if (![QGUitility directoryExist:cacheDir]) {
        [QGUitility createDirectory:cacheDir];
    }
    
    return [cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.md5",userId]];
}

- (void)saveUserPassword:(NSString *)userId password:(NSString *)password
{
    NSString *passKey = [NSString stringWithFormat:@"%@_kZYUserCenterLastLoginUserPassUDF",userId];
    
    [QGUitility userDefaultCache:password key:passKey];
}

- (NSString *)getUserPassword:(NSString *)userId
{
    NSString *passKey = [NSString stringWithFormat:@"%@_kZYUserCenterLastLoginUserPassUDF",userId];
    
    return [QGUitility userDefaultGetValue:passKey];
}

- (NSString *)getLastUserPassword
{
    return [self getUserPassword:self.innerLoginUser.mobile];
}

- (void)updateNickname:(NSString *)nickname
{
    if ([QGUitility stringIsNull:nickname]) {
        return;
    }
    
    self.innerLoginUser.nickname = nickname;
    
    [self saveCurrentLoginUser];
}

- (void)updateAvatar:(NSString *)imageUrl
{
    if ([QGUitility stringIsNull:imageUrl]) {
        return;
    }
    
    self.innerLoginUser.headThumb = imageUrl;
    
    [self saveCurrentLoginUser];
}

- (void)saveCurrentLoginUser
{
    if (!self.innerLoginUser) {
        return;
    }
    [self setupUserExtendInfo];
    
    NSDictionary *userInfo = [self.innerLoginUser mj_keyValues];
    
    NSData *userData = [NSKeyedArchiver archivedDataWithRootObject:userInfo];
    
    [userData writeToFile:[self userSavePath:self.innerLoginUser.userId] atomically:YES];
    
    [QGUitility userDefaultCache:self.innerLoginUser.userId key:kZYUserCenterLastLoginUserUDF];
}

- (void)readLastLoginUser
{
    NSString *userId = [QGUitility userDefaultGetValue:kZYUserCenterLastLoginUserUDF];
    
    if ([QGUitility stringIsNull:userId]) {
        return;
    }
    
    NSData *userData = [NSData dataWithContentsOfFile:[self userSavePath:userId]];
    
    NSDictionary *userInfo = [NSKeyedUnarchiver unarchiveObjectWithData:userData];
    
    self.innerLoginUser = [QGUserModel mj_objectWithKeyValues:userInfo];
    [self setupUserExtendInfo];
}

- (void)autoLogin
{
    if (!self.innerLoginUser) {
        return;
    }
    
    NSString *password = [self getUserPassword:self.innerLoginUser.userId];
    [self loginEaseMobWithMobile:self.innerLoginUser.mobile password:password];
}

- (void)setupUserExtendInfo
{
    self.innerExtendUserInfo = [[QGMessageExtendUserModel alloc]init];
    self.innerExtendUserInfo.nickName = self.innerLoginUser.nickname;
    self.innerExtendUserInfo.sex = self.innerLoginUser.sex;
    self.innerExtendUserInfo.headThumb = self.innerLoginUser.headThumb;
    self.innerExtendUserInfo.userName = self.innerLoginUser.name;
}

- (QGMessageExtendUserModel *)extendUserInfo
{
    return self.innerExtendUserInfo;
}

- (void)loginEaseMobWithMobile:(NSString *)mobile password:(NSString *)password
{
    [QGUitility postNoti:QGUserCenterLoginEaseMobSuccessNoti withObject:@(2)];
    
    [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:mobile password:password completion:^(NSDictionary *loginInfo, EMError *error) {
        
        if (!error) {
            [QGUitility postNoti:QGUserCenterLoginEaseMobSuccessNoti withObject:@{@"state":@(1)}];
            
            NSLog(@"loginUser:%@",loginInfo);
            if (!self.innerLoginUser) {
                self.innerLoginUser = [[QGUserModel alloc]init];
                self.innerLoginUser.name = mobile;
                NSString *timeString = [QGUitility currentTimeStampString];
                self.innerLoginUser.nickname = [NSString stringWithFormat:@"中驰车福%@",[timeString substringFromIndex:timeString.length-4]];
                self.innerLoginUser.headThumb = @"http://imgsrc.baidu.com/forum/pic/item/9d82d158ccbf6c81f34d2e53bc3eb13533fa4016.jpg";
                self.innerLoginUser.sex = @"0";
            }
            self.innerLoginUser.userId = [loginInfo objectForKey:@"username"];
            self.innerLoginUser.mobile = self.innerLoginUser.userId;
            [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
            [QGNotificationCenter postNotificationName:QGUserCenterLoginEaseMobSuccessNoti object:@(1)];
            [self saveUserPassword:mobile password:password];
            [self saveCurrentLoginUser];
            
            NSLog(@"登录环信成功");
            
        }else{
            
            NSLog(@"登录环信失败");
            [QGUitility postNoti:QGUserCenterLoginEaseMobSuccessNoti withObject:@(0)];
        }
        
    } onQueue:nil];
}
@end
